/**
 * 设置面单获取平台
 */

import React, { useState, useEffect, useMemo } from 'react';
import CommonModal from '@/components/CommonModal';
import { Modal, Radio, message, Tooltip, Alert, Checkbox } from 'antd';
import { getNetFaceList, addNetworkFace } from '../../service';
import { faceOrderTypeName } from '@/utils/config';

export default ({ item, handleOk, handleCancel }) => {
  const [data, setData] = useState({});

  const [open, setOpen] = useState(false);

  const [isOk, setIsOk] = useState(false);

  useEffect(() => {
    setOpen(true);
    handleGetListData();
  }, []);

  const platformArr = useMemo(() => {
    const arr = Object.keys(data);
    if (arr.indexOf('5') > -1) {
      arr.splice(arr.indexOf('5'), 1);
      arr.unshift('5');
    }
    if (arr.indexOf('28') > -1) {
      arr.splice(arr.indexOf('28'), 1);
      arr.unshift('28');
    }
    // console.log(arr)
    return arr;
  }, [data]);

  //兼容  展示弹窗文案
  const showStatus = useMemo(() => {
    if (item.expressName) {
      if (
        item.expressName.includes('顺丰速运') ||
        item.expressName.includes('极兔速递')
      ) {
        return true;
      } else {
        return false;
      }
    } else {
      //公共弹窗
      return false;
    }
  }, [item]);

  //获取面单列表
  const handleGetListData = async () => {
    START_LOADING();
    const { data = {}, success } = await getNetFaceList({
      networkId: item.networkId,
    });
    if (success) {
      setData(data);
    }
    END_LOADING();
  };

  //点击确定
  const onOk = async () => {
    let arr = [];
    for (let i in data) {
      for (let k in data[i]) {
        if (data[i][k].isSelected == 1) {
          arr.push(data[i][k].id);
          if (i != 8 && i != 3) {
            break;
          }
        }
      }
    }
    if (arr.length == 0) {
      Modal.info({
        content: '请至少选择一个面单平台！',
      });
      return;
    }
    START_LOADING();
    const params = {
      faceBillIds: arr,
      networkId: item.networkId,
    };
    const res = await addNetworkFace(params);
    END_LOADING();
    if (res.success) {
      message.success('添加成功！');
      setOpen(false);
      setIsOk(true);
    }
  };

  //点击选择面单平台
  const handleChange = (e, v) => {
    const val = e.target.value;
    const obj = { ...data };
    const arr = [...obj[v]];
    for (let i in arr) {
      if (arr[i].id == val) {
        arr[i].isSelected = 1;
      } else {
        if (arr[i].isSelected == 1) {
          arr[i].isSelected = 2;
        }
      }
    }
    obj[v] = arr;
    setData(obj);
  };

  const handleChangeCheckbox = (selectArr, v) => {
    data[v].map((item) => {
      if (selectArr.includes(item.id)) {
        item.isSelected = 1;
      } else {
        item.isSelected = 2;
      }
    });
    setData({ ...data });
  };

  //获取选中的值
  const getValue = (val, bool) => {
    if (bool) {
      const ids = data[val]
        .filter((item) => item.isSelected == 1)
        .map((item) => item.id);
      return ids;
    }
    const arr = data[val];
    for (let i in arr) {
      if (arr[i].isSelected == 1) {
        return arr[i].id;
      }
    }
    return undefined;
  };

  const onCancel = () => {
    setOpen(false);
  }

  const afterClose = () => {
    if (isOk) {
      handleOk();
    } else {
      handleCancel();
    }
  }

  return (
    <CommonModal
      title="添加面单获取平台"
      open={open}
      onCancel={onCancel}
      onOk={onOk}
      afterClose={afterClose}
      width="768px"
    >
      <div style={{ overflow: 'auto' }} className={showStatus ? 'twoRow' : ''}>
        <div className="mb10">
          <Alert
            message={
              <>
                <div>
                  {showStatus && '①'}
                  每个快递网点每个平台最多只能添加1个面单获取平台；
                  {showStatus && (
                    <>
                      <br />
                      ②官网接口网点、三方平台网点，两者如果同时添加了，则优先按官网接口网点处理
                    </>
                  )}
                </div>
              </>
            }
            type="info"
            showIcon
          />
        </div>
        {platformArr.map((v) => (
          <div style={{ maxHeight: '286px', overflow: 'auto' }} key={v}>
            <h4 style={{ margin: '12px 0' }}>
              {v == 5 || v == 28 ? '官网接口' : faceOrderTypeName[v]}
            </h4>
            {v == 3 || v == 8 ? (
              <Checkbox.Group
                onChange={(e) => handleChangeCheckbox(e, v)}
                value={getValue(v, true)}
              >
                {data[v].map((k) => (
                  <Checkbox value={k.id} key={k.id}>
                    <Tooltip
                      title={
                        <div>
                          <div>联系人：{k.senderName || '-'}</div>
                          <div>电话：{k.senderMobile || '-'}</div>
                          <div>地址：{k.province} {k.city} {k.area} {k.detail}</div>
                        </div>
                        // <div>
                        //   {k.platformName +
                        //     '-' +
                        //     k.ecstoreName +
                        //     '-' +
                        //     k.networkName}
                        //   {k?.isFailure == 1 && (
                        //     <span className="common-color9">（已失效）</span>
                        //   )}
                        //   {k?.isFailure == 0 && (
                        //     <span className="common-color10">（正常）</span>
                        //   )}
                        // </div>
                      }
                    >
                      <div
                        style={{
                          display: 'flex',
                          width: '320px',
                          marginBottom: '8px',
                        }}
                      >
                        <div
                          style={{ maxWidth: '240px' }}
                          className="text-overflow"
                        >
                          {k.platformName}-{k.ecstoreName}-{k.networkName}
                        </div>
                        <div>
                          {k?.isFailure == 1 && (
                            <span className="common-color9">（已失效）</span>
                          )}
                          {k?.isFailure == 0 && (
                            <span className="common-color10">（正常）</span>
                          )}
                        </div>
                      </div>
                    </Tooltip>
                  </Checkbox>
                ))}
              </Checkbox.Group>
            ) : (
              <Radio.Group
                onChange={(e) => handleChange(e, v)}
                value={getValue(v)}
              >
                {data[v].map((k) => (
                  <Radio value={k.id} key={k.id}>
                    <Tooltip
                      title={
                        <div>
                          <div>联系人：{k.senderName || '-'}</div>
                          <div>电话：{k.senderMobile || '-'}</div>
                          <div>地址：{k.province} {k.city} {k.area} {k.detail}</div>
                        </div>
                        // <div>
                        //   {k.platformName +
                        //     '-' +
                        //     k.ecstoreName +
                        //     '-' +
                        //     k.networkName}
                        //   {k?.isFailure == 1 && (
                        //     <span className="common-color9">（已失效）</span>
                        //   )}
                        //   {k?.isFailure == 0 && (
                        //     <span className="common-color10">（{k?.isUpDoor ? '送货上门' : '正常'}）</span>
                        //   )}
                        // </div>
                      }
                    >
                      <div
                        style={{
                          display: 'flex',
                          width: '320px',
                          marginBottom: '8px',
                        }}
                      >
                        <div
                          style={{ maxWidth: '240px' }}
                          className="text-overflow"
                        >
                          {k.platformName}-{k.ecstoreName}-{k.networkName}
                        </div>
                        <div>
                          {k?.isFailure == 1 && (
                            <span className="common-color9">（已失效）</span>
                          )}
                          {k?.isFailure == 0 && (
                            <span className="common-color10">（{k?.isUpDoor ? '送货上门' : '正常'}）</span>
                          )}
                        </div>
                      </div>
                    </Tooltip>
                  </Radio>
                ))}
              </Radio.Group>
            )}
          </div>
        ))}
        {platformArr.length == 0 && '暂无可用面单平台'}
      </div>
    </CommonModal>
  );
};
